package com.hna.cums.web.ImageSvrlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.BasicHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.InputStreamBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;
import com.hna.utils.HiveTempUtils;;

public class ImageCtrl extends HttpServlet {
	/** 日志 */
	static final Logger logger = LoggerFactory.getLogger(ImageCtrl.class);
	private InputStream in;
	static HiveTempUtils HiveCtx = null;
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
		JSONObject resultObj = new JSONObject();
		logger.error("get file success");
		
		// 得到上传文件的保存目录，将上传的文件存放于WEB-INF目录下，不允许外界直接访问，保证上传文件的安全
		String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");
		File file = new File(savePath);
		// 判断上传文件的保存目录是否存在
		if (!file.exists() && !file.isDirectory()) {
			logger.info(savePath + "目录不存在，需要创建");
			// 创建目录
			file.mkdir();
		}
		
		// FileOutputStream out;
		// ByteArrayOutputStream in;
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 解决上传文件名的中文乱码
			upload.setHeaderEncoding("UTF-8");

			// 判断提交上来的数据是否是上传表单的数据
			if (!ServletFileUpload.isMultipartContent(request)) {
				// 按照传统方式获取数据
				return;
			}

			List<FileItem> list = upload.parseRequest(request);

			for (FileItem item : list) {
				// 如果fileitem中封装的是普通输入项的数据
				if (item.isFormField()) {
					String name = item.getFieldName();
					// 解决普通输入项的数据的中文乱码问题
					String value = item.getString("UTF-8");
					// value = new String(value.getBytes("iso8859-1"),"UTF-8");
					logger.debug(name + "=" + value);
				} else {// 如果fileitem中封装的是上传文件
					// 得到上传的文件名称，
					String filename = item.getName();
					logger.debug(filename);
					if (filename == null || filename.trim().equals("")) {
						continue;
					}
					// 注意：不同的浏览器提交的文件名是不一样的，有些浏览器提交上来的文件名是带有路径的，如：
					// c:\a\b\1.txt，而有些只是单纯的文件名，如：1.txt
					// 处理获取到的上传文件的文件名的路径部分，只保留文件名部分
					filename = filename.substring(filename.lastIndexOf("\\") + 1);
					// 获取item中的上传文件的输入流
					in = item.getInputStream();
					long FileSize = item.getSize();
					//item.
					// // 创建一个文件输出流
					// out = new FileOutputStream(savePath + "\\" + filename);
					// // 创建一个缓冲区
					// byte buffer[] = new byte[1024];
					// // 判断输入流中的数据是否已经读完的标识
					// int len = 0;
					// // 循环将输入流读入到缓冲区当中，(len=in.read(buffer))>0就表示in里面还有数据
					// while ((len = in.read(buffer)) > 0) {
					// // 使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\"
					// // + filename)当中
					// out.write(buffer, 0, len);
					// }
					// // 关闭输入流
					// // in.close();
					//
					// // 关闭输出流
					// out.close();
					// 删除处理文件上传时生成的临时文件
					PostToArmby(FileSize, "aaaa");
					in.close();
					item.delete();
					logger.info("Upload Success!");
				}
			}
			response.setStatus(200);
			resultObj.put("status", "0");
			resultObj.put("message", "success");
			response.getWriter().print(resultObj);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			response.setStatus(500);
	
			resultObj.put("status", "501");
			resultObj.put("message", "FileUploadException");
			response.getWriter().print(resultObj);
			response.getWriter().flush();
			response.getWriter().close();
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			response.setStatus(500);
			resultObj.put("status", "501");
			resultObj.put("message", "IOException");
			response.getWriter().print(resultObj);
			response.getWriter().flush();
			response.getWriter().close();
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			response.setStatus(500);
			resultObj.put("status", "501");
			resultObj.put("message", "SQLException");
			response.getWriter().print(resultObj);
			response.getWriter().flush();
			response.getWriter().close();
			e.printStackTrace();
		}
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

	public Boolean PostToArmby(long FileSize, String UserID) throws SQLException {
		String Url = "http://10.71.200.109:1174";
		// URL restServiceURL;
		//Url = Url + URLEncoder.encode(in.toString().getBytes(), "UTF-8");;
		
		long sz = in.toString().length();
		
		CloseableHttpClient httpclient = HttpClients.createDefault();  
		HttpPost getRequest = new HttpPost(Url);
		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		
		try {			
			//getRequest.addHeader("accept", "application/octet-stream");
			getRequest.addHeader("Content-Type", "image/png");
			getRequest.addHeader("x-ambry-blob-size", String.valueOf(FileSize));//352938
			getRequest.addHeader("x-ambry-owner-id", UserID);
			getRequest.addHeader("x-ambry-service-id", "test111");
			getRequest.addHeader("x-ambry-content-type", "image/png");
			
			BasicHttpEntity myEntity = new BasicHttpEntity();
			myEntity.setContent(in);
			myEntity.setContentLength(FileSize);
			getRequest.setEntity(myEntity);
			
			CloseableHttpResponse response = httpclient.execute(getRequest);
			logger.debug("sz2: " + String.valueOf(sz));
			logger.debug("File_Size: " + String.valueOf(FileSize));
			if (response.getStatusLine().getStatusCode() != 201) {
				logger.debug("ambry error:"+ response.getStatusLine().getReasonPhrase());
				throw new RuntimeException("Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
			}

//			BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));
//
//			String output;
//			System.out.println("Output from Server .... \n");
//			while ((output = br.readLine()) != null) {
//				System.out.println(output);
//			}
			Header[] hd = response.getAllHeaders();
			String BlobID = "";
			for(int i = 0; i < response.getAllHeaders().length; i++){
				
				if( "Location".equals(hd[i].getName()) )
				{
					BlobID = hd[i].getValue();
					logger.debug(UserID + " put image location:" + BlobID);
					break;
				}
				continue;
			}
			
			httpclient.close();
			response.close();  
			if(HiveCtx == null ){
				HiveCtx = new HiveTempUtils("10.70.94.94:10000/default", "hive", "hive");
			}
			if( HiveCtx.IsConClosed()){
				logger.info("connect will be init!");
				HiveCtx.Conn();
			}
			
			String SqlString = String.format("insert into T_ImageInfo values('%s', null, null, null, null, '%s')", 
					BlobID, UserID);
			HiveCtx.RunCtx(SqlString);
			
			return true;
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			
			//we should delete image here
			e.printStackTrace();
		//	HiveCtx.closeStm();
			logger.error("error code : " + String.valueOf(e.getErrorCode()));
			return false;
		}

	}
}
